package cn.kgc.easybuy.service.impl;

import cn.kgc.easybuy.dao.UserMapper;
import cn.kgc.easybuy.exception.LoginUPException;
import cn.kgc.easybuy.pojo.User;
import cn.kgc.easybuy.service.LoginService;
import cn.kgc.easybuy.utils.JwtUtil;
import cn.kgc.easybuy.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: yingzi-wants-to-sleep
 * @description:
 * @author: 敖成
 * @create: 2025-09-16 09:05
 **/
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Map<String, Object> login(String loginName, String password) {
        User user = userMapper.login(loginName);
//        String sign = Sm3.sm3(password);
        String md5Password = SecurityUtils.md5Hex(password);
        if(user == null || !md5Password.equals(user.getPassword())) {
            throw new LoginUPException("用户名或密码错误！");
        }
        String jwt = JwtUtil.createToken((long)user.getId(),(long)user.getType());
        redisTemplate.opsForValue().set(user.getId().toString(), jwt, 30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jwt", jwt);
        map.put("userName",user.getUserName());
        return map;
    }
}
